package com.example.mybatisdemo.service.impl;

import com.dtflys.forest.ssl.TrustAllManager;
import com.example.mybatisdemo.config.FtpConfig;
import com.example.mybatisdemo.utils.FTPUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.InputStream;
import java.security.SecureRandom;

@Slf4j
@Service
public class FtpService {

    @Autowired
    private FtpConfig ftpConfig;

    public void uploadFile(String remotePath, MultipartFile file) throws Exception {
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom());
        FTPSClient ftpClient = new FTPSClient(true,sslContext);
//        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");


        try {
            ftpClient.connect(ftpConfig.getServer(), ftpConfig.getPort());
            ftpClient.login(ftpConfig.getUser(), ftpConfig.getPassword());

            int replyCode = ftpClient.getReplyCode();

            if(!FTPReply.isPositiveCompletion(replyCode)){
                log.error("FTP服务（{}:{}）连接失败。", ftpConfig.getServer(), ftpConfig.getPort());
                throw new Exception("FTP服务连接失败");
            }
            log.info("FTP服务（{}:{}）连接成功。", ftpConfig.getServer(), ftpConfig.getPort());

            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            try (InputStream inputStream = file.getInputStream()) {
                FTPUtil.ensureParentDirectoryExists(ftpClient,remotePath);
                boolean done = ftpClient.storeFile(new String(remotePath.getBytes("UTF-8"),"iso-8859-1"), inputStream);
                if (done) {
                    log.info("File " + file.getOriginalFilename() + " has been uploaded successfully.");
                } else {
                    throw new RuntimeException("Failed to upload file " + file.getOriginalFilename());
                }
            }
        } catch (Exception e){
            log.error("上传文件到ftp失败",e);
        } finally {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
    }



    private static class TrustAllTrustManager extends TrustAllManager {
        private static final TrustAllTrustManager INSTANCE = new TrustAllTrustManager();

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }
}
